/*
 * MailProcess.java
 *
 * Created on August 14, 2009, 3:22 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package apt.epj4.util;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author NGUYENVANHUNG
 */
public class MailProcess {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String SMTP_AUTH_USER = "group50.c0801l";
    private static final String SMTP_AUTH_PWD = "123c0801l";

    public boolean sendSSLMail(String from, String receiverList[], String subject,
            String body) throws MessagingException {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST_NAME);
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true");
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.socketFactory.port", SMTP_PORT);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");

            Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
                }
            });
            session.setDebug(true);
            MimeMessage msg = new MimeMessage(session);

            InternetAddress addressFrom = new InternetAddress(from);
            InternetAddress[] addressTo = new InternetAddress[receiverList.length];
            for (int i = 0; i < receiverList.length; i++) {
                addressTo[i] = new InternetAddress(receiverList[i]);
            }

            msg.setFrom(addressFrom);
            msg.setRecipients(Message.RecipientType.TO, addressTo);
            msg.setSubject(ConvertBetweenUnicodeNCR.NCR2Unicode(subject), "UTF-8");
            msg.setText(body);
            msg.setSentDate(new Date());
            msg.setHeader("Content-Type", "text/html; charset=UTF-8");
            msg.saveChanges();
            Transport.send(msg);
            System.out.println("Send mail successful!");
            
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
}
